<script lang="ts" setup>
  import { onMounted, reactive, ref, watch } from 'vue'
  import resconfig from '@/api/userService'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules, Action } from 'element-plus'
  import { useRouter } from 'vue-router'
  import { encryptedData } from '@/api/crypto'
  const router = useRouter()
  let nuserData = reactive({
    data: {
      username: '',
      password: '',
      email: '',
      phone: '',
      usertype: 0,
      activation: 0
    }
  })
  const autoScalingRef = ref<FormInstance>()
  const rules = reactive<FormRules>({
    username: [
      {
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
      },
      {
        pattern: /^[a-zA-Z][a-zA-Z0-9]{3,30}$/,
        message: '用户名由数字、字母组成，且必须包含一个字母，允许最短长度为四个字母',
        trigger: 'blur'
      }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      {
        pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@!%*#?&\.])[A-Za-z\d$@!%*#?&\.]{8,}$/,
        message: '至少8个字符，至少1个字母，1个数字和1个特殊字符(特殊字符包括：$@!%*#?&.)',
        trigger: 'blur'
      }
    ],
    phone: [
      {
        pattern: /^(1[2-9][0-9])\d{8}$/,
        message: '手机号码格式不正确！',
        trigger: 'blur'
      }
    ],
    email: [
      {
        pattern: /^\w+@\w+(\.\w+)+$/,
        message: '电子邮件格式不正确！',
        trigger: 'blur'
      }
    ]
  })

  const param = reactive({
    resconfig: {
      username: '',
      password: '',
      email: '',
      phone: '',
      usertype: 0,
      activation: 0
    }
  })
  let creating = ref(false)
  const onSubmit = async (formEl: FormInstance | undefined) => {
    if (creating.value) return
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        param.resconfig = JSON.parse(JSON.stringify(nuserData.data))
        param.resconfig.password = encryptedData(param.resconfig.password)
        try {
          creating.value = true
          let res = await resconfig.addUser(param)
          if (res.status < 300) {
            creating.value = false
            ElMessage({
              message: '创建成功',
              type: 'success'
            })
            localStorage.removeItem('nuserData')
            ElMessageBox.confirm('是否为当前用户创建租户？', '提示', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(async () => {
                localStorage.setItem(
                  'insertData',
                  JSON.stringify({
                    id: res.data.Id,
                    name: res.data.UserName
                  })
                )
                router.push({ name: 'insertResourceConfig' })
              })
              .catch(() => {
                router.push({ name: 'userMgmtList' })
              })
          }
        } catch (err) {
          creating.value = false
          ElMessage.error('创建失败')
        }
      } else {
        ElMessage({
          message: '请检查参数',
          type: 'warning'
        })
      }
    })
  }
  const onReset = () => {
    nuserData.data = {
      username: '',
      password: '',
      email: '',
      phone: '',
      usertype: 0,
      activation: 0
    }
  }
  watch(
    () => nuserData.data,
    (newValue, oldValue) => {
      localStorage.setItem('nuserData', JSON.stringify(newValue))
    },
    { deep: true }
  )
  const backUserInfo = () => {
    router.push({ name: 'userMgmtList' })
  }
  onMounted(() => {
    if (localStorage.getItem('nuserData')) {
      nuserData.data = JSON.parse(localStorage.getItem('nuserData') as string)
    }
  })
</script>
<template>
  <div id="createFleet" class="create-index">
    <div class="create-box">
      <span>新建用户</span>
      <span class="back" style="font-size: 14px; margin-left: -11px" @click="backUserInfo">&lt;&nbsp;返回</span>
    </div>
    <div class="form-box">
      <el-form ref="autoScalingRef" :model="nuserData.data" label-width="140px" label-position="left" :inline="true" :rules="rules" class="ac-form">
        <div class="card-box">
          <div class="card-content">
            <el-form-item prop="username">
              <template #label>
                <div class="item-label">用户名</div>
              </template>
              <el-input v-model="nuserData.data.username" maxlength="1024" />
            </el-form-item>
            <el-form-item prop="password">
              <template #label>
                <div class="item-label">密码</div>
              </template>
              <el-input v-model="nuserData.data.password" type="password" maxlength="1024" show-password />
            </el-form-item>
            <el-form-item prop="phone">
              <template #label>
                <div class="item-label">电话</div>
              </template>
              <el-input v-model="nuserData.data.phone" />
            </el-form-item>
            <el-form-item prop="email">
              <template #label>
                <div class="item-label">电子邮件</div>
              </template>
              <el-input type="email" v-model="nuserData.data.email" maxlength="1024" />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div class="operateButton">
        <el-button class="btn button" @click="onReset">重置</el-button>
        <el-button class="btn new button" type="primary" @click="onSubmit(autoScalingRef)">创建</el-button>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  @import '@/assets/scss/create.scss';
</style>
